from flask import Blueprint, render_template, request, jsonify
from app.models import db, Environment
from datetime import datetime

# 创建蓝图
env_bp = Blueprint('environment', __name__, url_prefix='/environment')

@env_bp.route('/')
def list_environments():
    """环境列表页面"""
    environments = Environment.query.order_by(Environment.name).all()
    env_list = [env.to_dict() for env in environments]
    
    # 检查请求是否是AJAX请求
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return jsonify({'environments': env_list})
    
    return render_template('environment/index.html', environments=env_list)

@env_bp.route('/data')
def get_environments():
    """获取环境列表数据"""
    # 获取查询参数
    search = request.args.get('search', '')
    
    # 构建查询
    query = Environment.query
    
    # 搜索过滤
    if search:
        query = query.filter(
            (Environment.name.ilike(f'%{search}%')) |
            (Environment.description.ilike(f'%{search}%'))
        )
    
    # 获取所有环境
    environments = query.order_by(Environment.name).all()
    
    # 构建响应数据
    env_list = [env.to_dict() for env in environments]
    
    return jsonify({
        'environments': env_list
    })

@env_bp.route('/', methods=['POST'])
def create_environment():
    """创建环境"""
    data = request.json
    if not data:
        return jsonify({
            'success': False,
            'message': '无效的请求数据'
        }), 400
    
    # 创建环境
    env = Environment(
        name=data.get('name', ''),
        description=data.get('description', ''),
        base_url=data.get('base_url', ''),
        variables=data.get('variables', {}),
        headers=data.get('headers', {})
    )
    
    db.session.add(env)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '环境创建成功',
        'environment': env.to_dict()
    })

@env_bp.route('/<int:env_id>', methods=['GET'])
def get_environment(env_id):
    """获取环境详情"""
    env = Environment.query.get_or_404(env_id)
    return jsonify({
        'success': True,
        'environment': env.to_dict()
    })

@env_bp.route('/<int:env_id>', methods=['PUT'])
def update_environment(env_id):
    """更新环境"""
    env = Environment.query.get_or_404(env_id)
    data = request.json
    if not data:
        return jsonify({
            'success': False,
            'message': '无效的请求数据'
        }), 400
    
    # 更新环境
    env.name = data.get('name', env.name)
    env.description = data.get('description', env.description)
    env.base_url = data.get('base_url', env.base_url)
    
    # 处理variables和headers（来自index.html模板的编辑功能）
    if 'variables' in data:
        env.variables = data.get('variables', env.variables)
    if 'headers' in data:
        env.headers = data.get('headers', env.headers)
    
    # 处理config和auth_config（来自detail.html模板的编辑功能）
    if 'config' in data:
        env.config = data.get('config', env.config)
    if 'auth_config' in data:
        env.auth_config = data.get('auth_config', env.auth_config)
    
    env.updated_at = datetime.now()
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '环境更新成功',
        'environment': env.to_dict()
    })

@env_bp.route('/<int:env_id>', methods=['DELETE'])
def delete_environment(env_id):
    """删除环境"""
    env = Environment.query.get_or_404(env_id)
    
    db.session.delete(env)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '环境删除成功'
    })